package com.ctlele.team.space.adapter;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.PopupMenu;
import androidx.recyclerview.widget.RecyclerView;

import com.ctlele.team.space.R;
import com.ctlele.team.space.activity.BaseActivity;
import com.ctlele.team.space.api.Api;
import com.ctlele.team.space.api.Apis;
import com.ctlele.team.space.entity.vo.FileItemVo;
import com.ctlele.team.space.util.DateUtils;
import com.ctlele.team.space.widget.dialog.MsgDialog;
import com.ctlele.team.space.widget.dialog.TipsDialog;
import com.ctlele.team.space.widget.toast.IToast;
import com.squareup.picasso.Picasso;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

import okhttp3.Call;
import okhttp3.Response;

public class FileItemAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final String TAG = "FileItemAdapter";

    private final BaseActivity mActivity;

    private List<FileItemVo> mFileList;

    private Consumer<FileItemVo> mOnDirClick;

    private Consumer<FileItemVo> mOnFileClick;

    private Runnable mAfterDelete = () -> {
    };

    public FileItemAdapter(BaseActivity activity, List<FileItemVo> fileList) {
        mActivity = activity;
        mFileList = fileList;
    }

    public FileItemAdapter(BaseActivity activity) {
        mActivity = activity;
    }

    public void flushData(List<FileItemVo> fileList) {
        mFileList = fileList;
        mActivity.runOnUiThread(() -> {
            notifyDataSetChanged();
        });
        IToast.success(mActivity, "数据刷新成功");
    }

    public void appendData(List<FileItemVo> fileList) {
        if (fileList == null || fileList.isEmpty()) {
            IToast.alert(mActivity, "没有更多数据");
            return;
        }
        if (mFileList == null || mFileList.isEmpty()) {
            flushData(fileList);
            return;
        }

        int size = mFileList.size();
        mFileList.addAll(fileList);
        mActivity.runOnUiThread(() -> {
            notifyItemRangeChanged(size, mFileList.size());
        });
    }

    public void setOnDirClick(Consumer<FileItemVo> task) {
        mOnDirClick = task;
    }

    public void setOnFileClick(Consumer<FileItemVo> task) {
        mOnFileClick = task;
    }

    private void onItemClick(Consumer<FileItemVo> task, FileItemVo item) {
        if (task != null) {
            task.accept(item);
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mActivity).inflate(R.layout.item_file_layout, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        ViewHolder vh = (ViewHolder) holder;
        FileItemVo item = mFileList.get(position);

        vh.filename.setText(item.getDocName());

        vh.remark.setText("");
        if (!TextUtils.isEmpty(item.getDocRemark())) {
            vh.remark.setText(item.getDocRemark());
            vh.remark.append(" ");
        }
        vh.remark.append(DateUtils.format(item.getGmtCreate()));

        if (!TextUtils.isEmpty(item.getThumbPath())) {
            vh.thumbImg.setScaleType(ImageView.ScaleType.FIT_CENTER);
            Picasso.with(mActivity).load(item.getThumbPath()).into(vh.thumbImg);
        } else if (item.getIsFile() == 0) {
            vh.thumbImg.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            vh.thumbImg.setImageResource(R.mipmap.file_dir);
        } else {
            vh.thumbImg.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            vh.thumbImg.setImageResource(R.mipmap.file_other);
        }
        vh.thumbImg.setOnClickListener(view -> {
            if (item.getIsFile() == 0) {
                onItemClick(mOnDirClick, item);
            } else {
                onItemClick(mOnFileClick, item);
            }
        });

        vh.moreImg.setOnClickListener(v -> popupMenu(v, item.getDocId()));

        vh.itemView.setOnLongClickListener(view -> {
            popupMenu(view, item.getDocId());
            return false;
        });
    }

    public void setAfterDelete(Runnable runnable) {
        mAfterDelete = runnable;
    }

    private void popupMenu(View view, String fileId) {
        PopupMenu popupMenu = new PopupMenu(mActivity, view);
        popupMenu.getMenuInflater().inflate(R.menu.menu_file_opt, popupMenu.getMenu());

        //弹出式菜单的菜单项点击事件
        popupMenu.setOnMenuItemClickListener(menuItem -> {
            TipsDialog tipsDialog = new TipsDialog(mActivity);
            tipsDialog.setTitle("提示");
            tipsDialog.setContent("是否要删除该文件？");
            tipsDialog.setOnOk(v -> {
                new Thread(() -> {
                    Api.deleteForm(mActivity, Apis.getUrlWithPathVariable(Apis.DELETE_FILE, fileId), new ArrayList<>(), new Api.ApiCallback() {
                        @Override
                        public void onFailure(Context context, Call call, IOException e) {
                            Log.e(TAG, e.getMessage(), e);
                        }

                        @Override
                        public void onResponse(Context context, Call call, Response response) {
                            mActivity.runOnUiThread(() -> mAfterDelete.run());
                        }
                    });
                }).start();
                tipsDialog.dismiss();
            });
            tipsDialog.show();
            return false;
        });
        popupMenu.show();
    }

    @Override
    public int getItemCount() {
        return mFileList == null ? 0 : mFileList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private final TextView filename;

        private final TextView remark;

        private final ImageView thumbImg;

        private final ImageView moreImg;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            filename = itemView.findViewById(R.id.filename);
            remark = itemView.findViewById(R.id.remark);
            thumbImg = itemView.findViewById(R.id.thumb_img);
            moreImg = itemView.findViewById(R.id.icon_more);

            itemView.setTag(this);
        }
    }
}
